package ljl.codetop300;

import commons.StupidAnswer;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

public class _71_simplify_path {

  /**
   * 这个感觉很简单，但是也没那么简单
   */
  @StupidAnswer(value = "非常糟糕的解法", stupidReason = "提交了七八次才通过了")
  static class test {
    public static void main(String[] args) {
      System.out.println(new test().simplifyPath("/a./././b/../../c/"));
    }

    public String simplifyPath(String path) {
      if (!path.endsWith("/")) path += '/';
      path = path.replaceAll("(?<=/)\\./", "/")
          .replaceAll("/{2,}", "/");
      if (path.length() == 1) return "/";
      String[] parts = path.substring(1, path.length() - 1).split("/");
      int j = -1;
      for (int i = 0; i < parts.length; i++) {
        if (!parts[i].equals("..")) {
          parts[++j] = parts[i];
        } else {
          j = Math.max(-1, j - 1);
        }
      }
      if (j == -1) return "/";
      StringBuilder sb = new StringBuilder();
      for (int i = 0; i <= j; i++) {
        sb.append("/").append(parts[i]);
      }
      return sb.toString();
    }
  }

  static class off1 {
    public String simplifyPath(String path) {
      String[] names = path.split("/");
      Deque<String> stack = new ArrayDeque<>();
      for (String name : names) {
        if ("..".equals(name)) {
          if (!stack.isEmpty()) {
            stack.pollLast();
          }
        } else if (name.length() > 0 && !".".equals(name)) {
          stack.offerLast(name);
        }
      }
      StringBuffer ans = new StringBuffer();
      if (stack.isEmpty()) {
        ans.append('/');
      } else {
        while (!stack.isEmpty()) {
          ans.append('/');
          ans.append(stack.pollFirst());
        }
      }
      return ans.toString();
    }
  }

  static class py4lines {
    public static void main(String[] args) {
      new py4lines().simplifyPath("/../");
    }
    public String simplifyPath(String path) {
      List<String> l = new ArrayList<>();
      String[] parts = path.split("/");
      for (String part : parts) {
        if (part.equals("") || part.equals(".")) continue;
        if (part.equals("..")) {
          if (l.size() > 0)
            l.remove(l.size() - 1);
        }
        else l.add(part);
      }
      return "/" + String.join("/", l);
    }
  }

}
